package com.example.lib_cache.viewmodel;

import android.content.Context;
import android.util.Log;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.lib_cache.model.Passwords;
import com.example.lib_cache.network.exception.ApiException;
import com.example.lib_cache.network.exception.ErrorConsumer;
import com.example.lib_cache.network.response.ResponseResultTransformer;
import com.example.lib_cache.service.ApiService;

import io.reactivex.functions.Consumer;

public class PasswordEditActivityViewModel extends ViewModel {

    private final static String TAG = PasswordEditActivityViewModel.class.getSimpleName();
    private MutableLiveData<Boolean> result = new MutableLiveData<>();
    private String oldPassword = "";
    private String confirmPassword = "";

    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }

    public void setOldPassword(String oldPassword){
        this.oldPassword = oldPassword;
    }


    public MutableLiveData<Boolean> getResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result.postValue(result);
    }

    public void requestUpdatePassWord(ApiService apiService, Context context){
        if("".equals(oldPassword)||"".equals(confirmPassword)){
            Log.d(TAG,"存在不规范的密码");
            return;
        }
        Passwords passwords = new Passwords();
        passwords.setOldPassword(oldPassword);
        passwords.setConfirmPassword(confirmPassword);
        apiService.changePassword(passwords)
                .compose(ResponseResultTransformer.<String>obtain())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Log.d(TAG,"修改成功");
                        setResult(true);
                    }
                }, new ErrorConsumer(context) {
                    @Override
                    protected void error(ApiException ex) {
                        Log.d(TAG, "修改失败");
                        Log.d(TAG, ex.getCode());
                        Log.d(TAG, ex.getErrorMsg());
                        if (ex.getCode().equals("501")) {
                            setResult(false);
                        }
                    }
                });
    }
}
